<template>
  <div>
    <!-- 1.导航栏 -->
    <van-nav-bar title="搜索中心" left-arrow @click-left="$router.back()" />
    <!-- 2.搜索栏 -->
    <van-search
      v-model="value"
      show-action
      placeholder="请输入搜索关键字"
      @search="onSearch"
      @input="onInput"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>
    <!-- 3.搜索结果 -->
    <van-cell-group>
      <van-cell v-for="(item, index) in showList" :key="index" icon="search"
      @click="$router.push({path:'/searchResult',query:{q:list[index]}})">
        <template #title>
          <div v-html="item"></div>
        </template>
      </van-cell>
    </van-cell-group>
    <!-- 4.历史记录 -->
    <van-cell-group>
      <van-cell title="历史记录"> </van-cell>
      <van-cell title="前端">
        <van-icon name="close" />
      </van-cell>
      <van-cell title="vue">
        <van-icon name="close" />
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
// 导入接口
import { getSuggestionList } from "./home.js";
export default {
  name: "search",
  data() {
    return {
      value: "",
      list: [],
    };
  },
  methods: {
    //1.输入框回车键  或  点击搜索按钮触发
    onSearch() {
      console.log(this.value);
      // 跳转搜索结果页
      this.$router.push({ path: "/searchResult", query: { q: this.value } });
    },

    // 2.输入框文本变化
    async onInput() {
      //   console.log("input:" + this.value);
      // 函数防抖处理
      //( 1)间隔时间内,多次触发事件清除上一次定时器,最后一次为准
      clearTimeout(this.timeID);
      // (2)开启防抖定时器
      this.timeID = setTimeout(async () => {
        // 2.1非空判断
        if (this.value.length == 0) {
          this.list = [];
          return;
        }
        // 2.2搜索推荐词
        let res = await getSuggestionList(this.value);
        console.log(res);
        this.list = res.data.data.options;
      }, 500);
    },
  },
  computed: {
    showList() {
      return this.list.map((item) => {
        let regexp = new RegExp(this.value, "ig");
        return item.replace(regexp, (match) => {
          return `<span style="color:red">${match}</span>`;
        });
      });
    },
  },
};
</script>

<style>
</style>